//
//  SHNavigationController.m
//  ShinyOrder
//
//  Created by 王方伟 on 16/7/22.
//  Copyright © 2016年 ShinyHub. All rights reserved.
//

#import "SHNavigationController.h"
#import "UIBarButtonItem+Extension.h"
#import "MainLib.h"

@interface SHNavigationController ()<UINavigationControllerDelegate, UIGestureRecognizerDelegate>

@end

@implementation SHNavigationController

+ (void)initialize{
    // 1.设置导航栏主题
    [self setupNavBarTheme];
}

- (void)viewDidLoad{
    [super viewDidLoad];
    __weak typeof(self) weakSelf = self;
    if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)]){
        self.interactivePopGestureRecognizer.delegate = weakSelf;
        self.delegate = self;
    }
}


#pragma mark 设置导航栏主题
+ (void)setupNavBarTheme{
    // 取出appearance对象
    UINavigationBar *navBar = [UINavigationBar appearance];
    // 设置标题属性
    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    textAttrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
    textAttrs[NSFontAttributeName] = [UIFont systemFontOfSize:17];
    [navBar setTitleTextAttributes:textAttrs];
}

    
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
    if (self.viewControllers.count > 0) {
        viewController.hidesBottomBarWhenPushed = YES;
        MainLib *main = [MainLib shareInstance];
        if (main.backBarItem) {
            viewController.navigationItem.leftBarButtonItem = main.backBarItem;
        }else if (main.backImage || main.backTitle){
            viewController.navigationItem.leftBarButtonItem = [UIBarButtonItem sh_itemWithTitle:main.backTitle titleColor:main.backColor titleFont:main.backFont icon:main.backImage highIcon:main.backImage target:self action:@selector(onClickBack)];
        }
    }
    [super pushViewController:viewController animated:YES];
}

- (UIViewController *)childViewControllerForStatusBarStyle{
    return self.topViewController;
}

#pragma mark 返回
- (void)onClickBack{
    [self popViewControllerAnimated:YES];
}


#pragma mark UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    // 删除系统自带的tabBarButton
    for (UIView *tabBar in self.tabBarController.tabBar.subviews) {
        if ([tabBar isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            [tabBar removeFromSuperview];
        }
    }
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    // 如果根控制器也要返回手势有效, 就会造成假死状态
    // 所以, 需要过滤根控制器
    if(self.childViewControllers.count == 1) {
        return NO;
    }
    return YES;
    
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
